//
//  File.swift
//  fphonelocation
//
//  Created by yfwl on 2024/2/1.
//

import Foundation
import CoreLocation
import Flutter

class CLLocationManagerUtil: NSObject ,CLLocationManagerDelegate{
    
    private var isSingle : Bool = false
    
    private var delayMilTime : Int = 50000
    
    //定位管理器
    private var locationManager:CLLocationManager?
    
    private var methodChannel : FlutterMethodChannel?
    
    private var canLocation : Bool = false
    
//    private var timer: Timer?
    
    init(binaryMessenger : FlutterBinaryMessenger) {
        super.init()
        
        self.methodChannel = FlutterMethodChannel(name: "com.lx.fnativelocation", binaryMessenger: binaryMessenger)
        self.methodChannel!.setMethodCallHandler(handMethodCallHandler)
        //设置定位服务管理器代理
            locationManager = CLLocationManager()
           locationManager!.delegate = self
           //设置定位进度
           locationManager!.desiredAccuracy = kCLLocationAccuracyBest
           //更新距离
           locationManager!.distanceFilter = 0
           //发送授权申请
            locationManager!.requestWhenInUseAuthorization()
            //停止使用后台连续定位，从而采取定时任务来模拟连续定位，以防上架被拒
//           locationManager!.requestAlwaysAuthorization()
//           locationManager!.allowsBackgroundLocationUpdates=true
           // 进入后台后不停止
//           locationManager!.pausesLocationUpdatesAutomatically = true
           if (CLLocationManager.locationServicesEnabled())
           {
               //允许使用定位服务的话，开启定位服务更新
               print("可以定位")
           }
    }
    
    public func handMethodCallHandler(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
      switch call.method {
      case "init":
          print("initFN---->init")
          initFN(arguments: call.arguments)
          break;
      case "startLocation":
          print("initFN---->startLocation isSingle=\(self.isSingle),delayMilTime=\(self.delayMilTime)")
          startRequestLocation()
          break;
      case "stopLocation":
          stopLocation()
          break;
      default:
        result(FlutterMethodNotImplemented)
      }
    }
    private func initFN(arguments : Any?){
        
        if let args = arguments as? Dictionary<String,Any>{
            self.isSingle = args["isSingle"] as! Bool
            self.delayMilTime = args["delayMilTime"] as! Int
        }
        print("initFN---->1 isSingle=\(self.isSingle),delayMilTime=\(self.delayMilTime)")
        self.startRequestLocation()
    }
    
    // 开始尝试获取定位
        public func startRequestLocation() {
            print("initFN---->startRequestLocation isSingle=\(self.isSingle),delayMilTime=\(self.delayMilTime)")
            self.canLocation = true
            if (self.locationManager != nil) && (CLLocationManager.authorizationStatus() == .denied) {
                // 没有获取到权限，再次请求授权
                print("拒绝授权")
                if(self.locationManager != nil){
                    self.locationManager!.requestWhenInUseAuthorization()
                }
            } else {
                print("开始定位")
                // 调用loadData函数并设置延迟为1秒
                self.setLocationLoop()
            }
        }
    
    public func setLocationLoop(){
        print("initFN---->定位 isSingle=\(self.isSingle),delayMilTime=\(self.delayMilTime)")
        print("---->开始定位")
        if(self.isSingle == false){
            if(self.canLocation == true){
                
                let delay = DispatchTimeInterval.seconds(self.delayMilTime/1000)
                DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
                    self.startUpdatingLocation()
                }
            }
            print("initFN---->isSingle=\(self.isSingle),delayMilTime=\(self.delayMilTime) loop")
        }else{
            self.startUpdatingLocation()
            print("initFN---->isSingle=\(self.isSingle),delayMilTime=\(self.delayMilTime)")
        }
        
    }
    public func startUpdatingLocation(){
        if(self.locationManager != nil){
            self.locationManager!.startUpdatingLocation()
            self.locationManager!.stopUpdatingLocation()
        }
    }
    public func stopLocation(){
        self.canLocation = false
        if(self.locationManager != nil){
            print("---->停止定位")
            self.locationManager!.stopUpdatingLocation()
        }
    }
        //定位改变执行，可以得到新位置、旧位置
        public  func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            //获取最新的坐标
            print("获取定位结果")
            let currLocation:CLLocation = locations.last!
            print("获取定位结果")
            print("经度：\(currLocation.coordinate.longitude)\n经度：\(currLocation.coordinate.longitude)\n海拔：\(currLocation.altitude)\n水平精度：\(currLocation.horizontalAccuracy)\n垂直精度：\(currLocation.verticalAccuracy)\n方向：\(currLocation.course)\n速度：\(currLocation.speed)")
            
            if(methodChannel != nil){
                var parms = [String:Double]()
                parms["latitude"] = currLocation.coordinate.latitude
                parms["longitude"] = currLocation.coordinate.longitude
                
                methodChannel?.invokeMethod("locationCall", arguments: parms)
            }
            self.startRequestLocation()
            
        }
        // 代理方法，当定位授权更新时回调
        public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
            print("授权变化")
            // CLAuthorizationStatus
            // .notDetermined   用户还没有选择授权
            // .restricted   应用没有授权用户定位
            // .denied 用户禁止定位
            // .authorizedAlways 用户授权一直可以获取定位
            // .authorizedWhenInUse 用户授权使用期间获取定位
            // TODO...
            if status == .notDetermined {
                //未授予
            } else if (status == .restricted) {
                // 受限制，尝试提示然后进入设置页面进行处理
                
            } else if (status == .denied) {
                // 被拒绝，尝试提示然后进入设置页面进行处理
                
            }else{
//                startRequestLocation()
            }
        }
        
        // 当获取定位出错时调用
        public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
            // 这里应该停止调用api
            print(error)
            print(error.localizedDescription)
            print("定位失败")
            self.stopLocation()
        }
}
